package com.fzu.normalservice.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fzu.commonutil.entity.Company;
import com.fzu.commonutil.mapper.DemandMapper;
import com.fzu.commonutil.params.DataResult;
import com.fzu.commonutil.util.JwtUtil;
import com.fzu.commonutil.util.RedisKey;
import com.fzu.commonutil.util.RedisUtil;
import com.fzu.normalservice.service.CompanyService;
import com.fzu.normalservice.service.DataService;
import com.fzu.normalservice.service.DemandService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;
import java.util.Set;

@Configuration
@EnableScheduling
@Slf4j
@RequiredArgsConstructor
public class TimeTask {

    private final DemandService demandService;
    private final RedisUtil redisUtil;
    private final DataService dataService;
    private final CompanyService companyService;


    /**
     * 每10分钟执行一次
     */
    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void timeout() {
        // 待匹配的需求数
        long waitMatchCount = redisUtil.sGetSetSize(RedisKey.WAIT_MATCH_DEMAND_ID);
        // 家政员信息是否发生变化
        boolean changeTag = redisUtil.hasKey(RedisKey.HOUSEKEEPER_CHANGE_TAG);
        log.info("需求匹配定时任务启动，匹配数: {}， 信息变化：{}", waitMatchCount, changeTag);
        // 匹配中需求数大于0，且家政员信息发生变化，执行匹配操作
        if (waitMatchCount > 0 && changeTag) {
            Set<Object> waitMatchDemandIds = redisUtil.sGet(RedisKey.WAIT_MATCH_DEMAND_ID);
            for (Object demandId : waitMatchDemandIds) {
                demandService.demandMatch((Integer) demandId);
            }
        }
        // 删除家政员信息变化标识
        redisUtil.del(RedisKey.HOUSEKEEPER_CHANGE_TAG);
    }

    /**
     * 更新数据大屏数据，每30分钟执行一次
     */
    @Scheduled(fixedRate = 30 * 60 * 1000)
    public void dataBoard() {
        DataResult data = dataService.data(null);
        redisUtil.set(RedisKey.NORMAL_DATA, data);
        List<Company> companyList = companyService.list(new LambdaQueryWrapper<>());
        for (Company company : companyList) {
            DataResult dataResult = dataService.data(company.getId());
            redisUtil.set(RedisKey.NORMAL_DATA + "_" + company.getId(), dataResult);
        }
    }
}
